package sample.ui

import android.content.Intent
import android.os.Bundle
import android.text.style.RelativeSizeSpan
import android.view.View
import android.view.ViewGroup
import android.view.ViewOutlineProvider
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import android.view.WindowManagerService
import com.netease.core.R
import com.tendcloud.tenddata.TalkingDataSDK
import eightbitlab.com.blurview.RenderScriptBlur
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.script.Controller
import kotlinx.coroutines.script.GComponents
import kotlinx.coroutines.script.tes.appBuildTime
import kotlinx.coroutines.script.tes.appDeviceId
import kotlinx.coroutines.script.tes.appScopeLaunch
import kotlinx.coroutines.script.tes.appVersionInfo
import kotlinx.coroutines.script.tes.colorInt
import kotlinx.coroutines.script.tes.phoneDefaultDisplayPoint
import kotlinx.coroutines.script.tes.phoneDensityDpi
import kotlinx.coroutines.script.tes.phoneScreenHeight
import kotlinx.coroutines.script.tes.phoneScreenWidth
import kotlinx.coroutines.script.tes.phoneVersionName
import kotlinx.coroutines.script.tes.printLog
import kotlinx.coroutines.script.tes.random
import kotlinx.coroutines.script.tes.readByDisk
import kotlinx.coroutines.script.tes.setOnClickCallback
import kotlinx.coroutines.script.tes.setupTouchScaleAnimation
import kotlinx.coroutines.script.tes.systemWindowInsetsTop
import kotlinx.coroutines.script.tes.toTime
import kotlinx.coroutines.script.tes.toast
import kotlinx.coroutines.script.tes.tryLaunchGame
import kotlinx.coroutines.script.tes.writeToDisk
import eightbitlab.com.blurview.BlurView
import kotlin.math.abs
import kotlin.math.floor
import kotlin.random.Random

class MainActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.i)

        val top = systemWindowInsetsTop
        findViewById<View>(R.id.fitsSys).setPadding(top / 2, top / 2, top / 2, top / 2)
        findViewById<ImageView>(R.id.bg).setImageResource(when(Random.nextInt(2)) {
            0 -> R.mipmap.bg1
            else -> R.mipmap.bg5
        })
        window.decorView.findViewById<ViewGroup>(android.R.id.content)?.also {  decorView ->
            arrayOf(findViewById(R.id.tipLayout), findViewById(R.id.captureLayout),
                findViewById(R.id.accessLayout), findViewById(R.id.cdkLayout),
                findViewById(R.id.funcTaskLayout), findViewById(R.id.funcWxPushLayout),
                findViewById(R.id.funcFeedbackLayout), findViewById(R.id.funcSettingsLayout),
                findViewById(R.id.funcEndLayout), findViewById<BlurView>(R.id.funcClearLayout)).forEach {
                it.setupWith(decorView, RenderScriptBlur(this)) // or RenderEffectBlur
                    .setFrameClearDrawable(decorView.background) // Optional
                    .setBlurRadius(5f)
                it.setBackgroundResource(R.drawable.corners_blur)
                it.outlineProvider = ViewOutlineProvider.BACKGROUND
                it.clipToOutline = true
                it.setupTouchScaleAnimation()
            }
        }
        val textList = listOf(
            "旨在让玩家脱离PVE辛苦劳动日常，留下更多时间精力来体验PVP对战的乐趣。",
        )
        var textIdx = random.nextInt(textList.size)
        findViewById<TextView>(R.id.tip).text = textList[textIdx%textList.size]
        val st =  readByDisk("serverTip")

        if (st?.isNotEmpty() == true) findViewById<TextView>(R.id.tip).text = st
        else findViewById<View>(R.id.tipLayout).setOnClickListener {
            findViewById<TextView>(R.id.tip).text = textList[(++textIdx)%textList.size]
        }
        findViewById<View>(R.id.accessLayout).setOnClickCallback {
            Permissions.requireAccessibilityPermission(this)
        }
        findViewById<View>(R.id.captureLayout).setOnClickCallback {
            Permissions.requireCaptureScreenPermission(this)
        }
        findViewById<View>(R.id.cdkLayout).setOnClickCallback {
            CKV2SetupDialogFragment().show(supportFragmentManager)
        }
        findViewById<View>(R.id.funcFeedbackLayout).setOnClickCallback {
            startActivity(Intent(this, LogActivity::class.java))
        }
//        findViewById<View>(R.id.funcWxPushLayout).setOnClickCallback {
//            WxPushSetupDialogFragment().show(supportFragmentManager)
//        }
        findViewById<View>(R.id.funcTaskLayout).setOnClickCallback {
            if (!Permissions.isCDKeyActivating) {
                CKV2SetupDialogFragment().show(supportFragmentManager)
            } else {
                SetupTaskDialog.Builder(it.context).create().show()
            }
        }
        findViewById<View>(R.id.funcSettingsLayout).setOnClickCallback {
            if (!Permissions.isCDKeyActivating) {
                CKV2SetupDialogFragment().show(supportFragmentManager)
            } else {
                SetupSettingsDialog.Builder(it.context).create().show()
            }
        }
        findViewById<View>(R.id.startView).setOnClickCallback {
            if (!Permissions.isIgnoringBatteryOptimizations) {
                PopAlert.Builder(this)
                    .setTitle("忽略系统电池优化")
                    .setMessage("请确保${getString(R.string.app_name)}进程存活")
                    .setPositiveButton("前往设置") { _, _ ->
                        appScopeLaunch(Dispatchers.Main) {
                            delay(300L)
                            Permissions.requireIgnoreBatteryOptimization(this@MainActivity)
                        }
                    }
                    .setNegativeButton("取消") { _, _ -> }
                    .show()
            } else if (!Permissions.isAlertWindowPermissionOpened) {
                PopAlert.Builder(this)
                    .setTitle("开启悬浮窗权限")
                    .setMessage("将菜单按钮悬浮在游戏之上;以便你操作控制")
                    .setPositiveButton("前往设置") { _, _ ->
                        appScopeLaunch(Dispatchers.Main) {
                            delay(300L)
                            Permissions.requireAlertWindowPermission(this@MainActivity)
                        }
                    }
                    .setNegativeButton("取消") { _, _ -> }
                    .show()
            } else if (!Permissions.isAccessibilityPermissionOpened) {
                if (readByDisk("hasRunningSuccess")?.isNotEmpty() == true) {
                    appScopeLaunch(Dispatchers.Main) {
                        delay(300L)
                        Permissions.requireAccessibilityPermission(this@MainActivity)
                    }
                } else { // 新手
                    PopAlert.Builder(this)
                        .setTitle("开启无障碍权限")
                        .setMessage("在游戏中下发手势执行代打操作\\n点击前往设置.找到无障碍服务并开启")
                        .setPositiveButton("前往设置") { _, _ ->
                            appScopeLaunch(Dispatchers.Main) {
                                toast("在页面底部已安装应用列表区域.授权${getString(R.string.app_name)}")
                                delay(300L)
                                Permissions.requireAccessibilityPermission(this@MainActivity)
                            }
                        }
                        .setNegativeButton("取消") { _, _ -> }
                        .show()
                }

            } else if (!Permissions.isCaptureAbilityEnable) {
                if (readByDisk("hasRunningSuccess")?.isNotEmpty() == true) {
                    appScopeLaunch(Dispatchers.Main) {
                        delay(300L)
                        Permissions.requireCaptureScreenPermission(this@MainActivity)
                    }
                } else { // 新手
                    PopAlert.Builder(this)
                        .setTitle("开启截屏权限")
                        .setMessage("识别并分析游戏内容")
                        .setPositiveButton("前往设置") { _, _ ->
                            appScopeLaunch(Dispatchers.Main) {
                                delay(300L)
                                Permissions.requireCaptureScreenPermission(this@MainActivity)
                            }
                        }
                        .setNegativeButton("取消") { _, _ -> }
                        .show()
                }
            } else if (!Permissions.isCDKeyActivating) {
                CKV2SetupDialogFragment().show(supportFragmentManager)
            } else if (Properties.scene.isEmpty() && Properties.area.isEmpty()) {
                SetupTaskDialog.Builder(it.context).create().show()
            } else {
                val r =  (phoneScreenWidth * 1f / phoneScreenHeight)
                val pxOk = phoneScreenWidth == 720 || phoneScreenHeight == 720 ||
                        phoneScreenWidth == 1080 || phoneScreenHeight == 1080 ||
                        abs(r - 0.5625f) < 0.05f || abs(r - 1.77f) < 0.05f
                if (!pxOk) toast("此分辨率可能无法正常运行")

                lifecycleScope.launch(Dispatchers.Main) {
                    Properties.setControllerRunning(false)
                    WindowManagerService.start(it.context)
                    delay(200)
                    tryLaunchGame() // 顺手启动游戏
                    delay(300)
                    finish()
                }
            }
        }
        findViewById<View>(R.id.funcList).setOnLongClickListener {
            toast(readByDisk("keyErr"))
            true
        }

        findViewById<View>(R.id.funcEndLayout).setOnClickCallback { WindowManagerService.stop(this) }
        findViewById<View>(R.id.funcClearLayout).setOnClickCallback { GComponents.clearGoDisk() }

        lifecycleScope.launch(Dispatchers.Main) {
            printLog { "Main try release GComponents by screenSize changed [ush:${Properties.usingScreenHeight}#psh:$phoneScreenHeight] [usw:${Properties.usingScreenWidth}#psh:$phoneScreenWidth]" }
            if (Properties.usingScreenHeight != phoneScreenHeight ||
                Properties.usingScreenWidth != phoneScreenWidth
            ) {
                // 模拟器切换了分辨率
                Properties.setUsingScreenWidth(phoneScreenWidth)
                Properties.setUsingScreenHeight(phoneScreenHeight)
                Controller.stopIfRunning("屏幕尺寸变化")
                delay(500)
                toast("屏幕尺寸发生了变化.清除初始化分析缓存")
                GComponents.clearGoDisk()
                printLog { "Main try release GComponents by screenSize changed released" }
            }
            delay(1)
        }

        TalkingDataSDK.onPageBegin(this, "Home")
        printLog { "H onCreate $appDeviceId" }
        Permissions.statusUpdated.observe(this) {
            displayText1()
        }
        if (System.currentTimeMillis() > (appBuildTime + (1001 * 86400000L))) {
            findViewById<TextView>(R.id.startView).also {
                it.text = "版本过低"
                it.setOnClickListener { toast("请更新版本") }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        displayText1()
        startCheckCDK()

        if (readByDisk("exitTip")?.isNotEmpty() == true) {
            writeToDisk("exitTip", "")
            startActivity(Intent(this, LogActivity::class.java))
        }
    }

    override fun onPause() {
        super.onPause()
        stopCheckCDK()
    }

    private fun displayText1() {
        val x = phoneDefaultDisplayPoint.x
        val y = phoneDefaultDisplayPoint.y
        val dpi = phoneDensityDpi
        val isOkPx = when {
            x == 1080 && (y in 1920..2800) -> true
            x == 720 && (y in 1280..1500) -> true
            x == 540 && y == 960 -> true
            y == 1080 && (x in 1920..2800) -> true
            y == 720 && (x in 1280..1500) -> true
            y == 540 && x == 960 -> true
            else -> false
        }
        val isAuthorPx = (x == 1080 && y == 1920) ||
                (x == 720 && y == 1280) ||
                (x == 540 && y == 960) ||
                (x == 1920 && y == 1080) ||
                (x == 1280 && y == 720) ||
                (x == 960 && y == 540)

        findViewById<TextView>(R.id.text1).also {
            it.text = "Android$phoneVersionName ${x}x${y} dpi$dpi $appVersionInfo"
            when {
                isAuthorPx -> it.setTextColor("#A5CA63".colorInt)
                isOkPx -> it.setTextColor("#8C8C8C".colorInt)
                else -> it.setTextColor("#CDB73C".colorInt)
            }
        }

        findViewById<TextView>(R.id.text2).text = Spanner().also {
            it.append("图色类按键精灵|无需Root权限|无内存修改\n游戏内画面品质低\n推荐设备分辨率 1280*720 dpi320")
            val t3 = readByDisk("t3")
            if (t3?.isNotEmpty() == true) it.append("|").append(t3)
        }

        val cdkAtv = Properties.ckV2Info != null
        findViewById<View>(R.id.cdkEmpty).isVisible = !cdkAtv
        findViewById<View>(R.id.cdkInfo)
        findViewById<TextView>(R.id.cdkInfo).also {
            it.isVisible = cdkAtv
            it.text = Spanner().also { text ->
                text.append("已激活", RelativeSizeSpan(1.5f),)
                text.append("\n")
                text.append("有效期至 ${Properties.ckV2Info?.expirationTime?.toTime("yyyy/MM/dd HH:mm")}")
                text.append("\n")

                val expiredTs = Properties.ckV2Info?.expirationTime
                if (expiredTs != null) {
                    val remainingTime = expiredTs - System.currentTimeMillis()
                    val left = if (remainingTime > 0) {
                        val days = floor((remainingTime / (1000 * 60 * 60 * 24)).toDouble()).toInt()
                        val hours = floor(((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toDouble()).toInt()
                        if (days > 0) "剩余${days}天${hours}小时"
                        else if (hours > 0) "剩余${hours}小时"
                        else "即将失效"
                    } else "已失效(点击更换新卡密)"
                    text.append(left)
                }
            }
        }
//        findViewById<TextView>(R.id.wxPushText).text = if (Properties.xtsToken.length == 25) "微信通知(已配置)" else "微信通知"
        findViewById<TextView>(R.id.taskName).text = "任务设置"
        if (Properties.scene.isNotEmpty()) findViewById<TextView>(R.id.taskName).text = Properties.scene
        else if (Properties.area.isNotEmpty()) findViewById<TextView>(R.id.taskName).text = "${Properties.area}\n${Properties.selectedChildAreaList.firstOrNull()}"
        printLog { "displayText1 isAccessibilityPermissionOpened ${Permissions}.isAccessibilityPermissionOpened" }
        findViewById<TextView>(R.id.accessText).text = if (Permissions.isAccessibilityPermissionOpened) "无障碍权限(已授权)" else "无障碍权限(未授权)"
        findViewById<TextView>(R.id.captureText).text = if (Permissions.isCaptureAbilityEnable) "截屏权限(已授权)" else "截屏权限(未授权)"
        findViewById<TextView>(R.id.clearAnaTip).text = if (readByDisk("GOSelfHpLeft").isNullOrEmpty()) "当前无缓存" else "重新初始化"
    }

    private var jobCheckCdk: Job? = null
    private fun startCheckCDK() {
        jobCheckCdk?.cancel()
        jobCheckCdk = lifecycleScope.launch(Dispatchers.Main) {
            while(true) {
                val out = Permissions.isCDKeyActivating
                printLog { "resumedCheckCDK $out" }
                Permissions.updateCDKeyActivating()
                delay(60000)
            }
        }
    }
    private fun stopCheckCDK() {
        jobCheckCdk?.cancel()
    }

    override fun onDestroy() {
        super.onDestroy()
        TalkingDataSDK.onPageEnd(this, "Home")
    }

}

